<!-- 
 
-->
<template>
  <DialogLayout ref="dialogRef" method="POST" path="/dev-api/oa/headcount" @submited="handlerDialogSubmited">
    <el-form-item label="项目">
      <el-select disabled v-model="form.projectId" placeholder="请选择项目" style="width: 100%"> <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" /> </el-select>
    </el-form-item>
    <el-form-item label="时间段" prop="timeSlot">
      <el-date-picker v-model="form.timeSlot" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
    </el-form-item>
    <el-form-item label="部门" prop="deptIds">
      <el-cascader disabled :options="deptList" :props="deptProps" v-model="form.deptIds" style="width: 100%" />
    </el-form-item>
    <el-form-item label="人数" prop="userNum">
      <el-input v-model="form.userNum" autocomplete="off" type="number" />
    </el-form-item>
    <template #footer>
      <el-button type="danger" @click="handleClickBtnDelete">删除</el-button>
    </template>
  </DialogLayout>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import DialogLayout from '../../layout/DialogLayout.vue'
import { FormRules } from 'element-plus'
import { useDeptStore, useUsersStore, useProjectssStore } from '../../stores'
import { formatDate, getWeeksBetweenDates } from '../../utils'
import http from '../../http'
import { ElMessage, ElMessageBox } from 'element-plus'

const emits = defineEmits(['submited'])
const deptProps = ref({ label: 'deptName', value: 'deptId' })
const deptList = ref(useDeptStore().getAllState())
const dialogRef = ref<InstanceType<typeof DialogLayout>>()
const projectssStore = useProjectssStore()
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(projectssStore.getAllState() as any)
const weeks = ref<{ start: Date; end: Date }[]>([])
const startDate = ref('')
const endDate = ref('')
const form = reactive({
  id: null,
  colId: -1,
  projectId: 0,
  projectCode: '',
  projectName: '',
  weekStartDate: '',
  weekEndDate: '',
  deptIds: [] as number[],
  deptId: -1,
  deptName: '',
  userNum: 0,
  createBy: useUsersStore().user.username,
  timeSlot: [] as Date[],
})
/**
 * 验证时间区间是否被占用
 *
 * @param rule 校验规则
 * @param value 校验值，应为包含两个时间戳的数组 [startTime, endTime]
 * @param callback 回调函数，验证通过时传入null，验证失败时传入错误信息
 */
const validateTimeSlot = (_: any, value: any, callback: any) => {
  //   weekStartDate.value = formatDate(value[0], 'yyyy-MM-dd')

  // weekEndDate.value = formatDate(value[1], 'yyyy-MM-dd')
  // console.log('startDate', startDate.value)
  // console.log('endDate', endDate.value)

  if (!value[0] && !value[1]) {
    callback(new Error('请选择时间段'))
  } else if (new Date(startDate.value).getTime() > new Date(value[0]).getTime() || new Date(endDate.value).getTime() < new Date(value[1]).getTime()) {
    callback(new Error(`时间区间必须在 ${formatDate(new Date(startDate.value), 'yyyy-MM-dd')} 到 ${endDate.value} 之间`))
  } else {
    callback()
  }
}

/**
 * 验证时间区间是否被占用
 *
 * @param rule 校验规则
 * @param value 校验值，应为包含两个时间戳的数组 [startTime, endTime]
 * @param callback 回调函数，验证通过时传入null，验证失败时传入错误信息
 */
const validateDept = (_: any, value: any, callback: any) => {
  // console.log('rule', rule)

  if (value.length < 3) {
    callback(new Error('请选择部门'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  timeSlot: [{ required: true, validator: validateTimeSlot, trigger: ['change', 'blur'] }],
  deptIds: [{ required: true, validator: validateDept, trigger: ['change', 'blur'] }],
  userNum: [
    {
      required: true,
      validator: (rule: any, value: number, callback: any) => {
        if (rule) {
        }
        if (value < 0) {
          callback(new Error('人数必须大于 0'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

/**
 * 构建请求参数
 *
 * @param start 开始日期
 * @param end 结束日期
 * @returns 请求参数对象
 */
const buildParams = (start: any, end: any) => {
  console.log('weeks', start, end)
  form.deptId = form.deptIds[form.deptIds.length - 1]
  const deptItem = useDeptStore().getDeptById(form.deptId)
  // form.deptName = deptItem.deptName
  // form.weekStartDate = start
  // form.weekEndDate = end
  return {
    weekStartDate: formatDate(start, 'yyyy-MM-dd'),
    weekEndDate: formatDate(end, 'yyyy-MM-dd'),
    projectId: form.projectId,
    projectCode: form.projectCode,
    projectName: form.projectName,
    deptId: form.deptId,
    deptName: deptItem.deptName,
    weekUserNum: form.userNum,
    createBy: form.createBy,
  }
}

const openDialog = (val: any) => {
  const { weekStartDate, weekEndDate, deptId, userNum, projectId, projectCode, projectName, flag, colId } = val
  startDate.value = weekStartDate
  endDate.value = weekEndDate
  const deptItem = useDeptStore().getDeptById(deptId)

  const arrFromA = deptItem.ancestors
    .split(',')
    .filter((item: any) => item !== '0')
    .map((strNum: any) => parseInt(strNum))

  form.colId = colId
  form.projectId = projectId
  form.deptId = deptId
  form.projectCode = projectCode
  form.projectName = projectName
  form.deptIds = [...arrFromA, deptId]
  form.timeSlot = [weekStartDate, weekEndDate]
  form.userNum = userNum
  const submitFunction = flag ? updateRequirement : addRequirement
  dialogRef.value?.openDialog({
    title: '编辑员工',
    class: 'dialog-add-headcount',
    form: form,
    rules: rules,
    submitFunction,
  })
}

/**
 * 异步更新需求
 *
 * @param callback - 回调函数，当操作完成后调用
 */
const updateRequirement = async (callback: Function) => {
  const res = await http({
    method: 'PUT',
    path: '/dev-api/oa/requirement',
    params: {
      id: form.colId,
      weekUserNum: form.userNum,
    },
  })
  if (res.code === 200) {
    ElMessage({
      message: `修改成功！`,
      grouping: true,
      type: 'success',
    })
  } else {
    ElMessage({
      message: `修改失败！`,
      grouping: true,
      type: 'error',
    })
  }
  callback()
}

/**
 * 异步添加需求
 *
 * @param callback 回调函数，添加需求完成后执行
 * @returns 无返回值
 */
const addRequirement = async (callback: Function) => {
  const res: any = []
  weeks.value = getWeeksBetweenDates(new Date(form.timeSlot[0]), new Date(form.timeSlot[1]))
  weeks.value.forEach(async (week: any) => {
    const params = buildParams(new Date(week.start), new Date(week.end))
    res.push(http({ method: 'POST', path: '/dev-api/oa/requirement', params }))
  })
  const requesets = await Promise.all(res)
  const result = requesets.reduce(
    (acc: any, obj: any) => {
      if (obj.code === 200) {
        acc.count200++
      }
      if (obj.code === 500) {
        acc.count500++
      }
      return acc
    },
    { count200: 0, count500: 0 }
  )
  if (weeks.value.length === result.count200) {
    ElMessage({
      message: `添加成功！`,
      grouping: true,
      type: 'success',
    })
  } else {
    ElMessage({
      message: `添加失败！成功：${result.count200}，失败：${result.count500}`,
      grouping: true,
      type: 'error',
    })
  }
  await callback()
}

const handlerDialogSubmited = (data: any) => {
  emits('submited', data)
}

const handleClickBtnDelete = async () => {
  ElMessageBox.confirm('确定要删除该条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await http({
        method: 'DELETE',
        path: `/dev-api/oa/requirement/${form.colId}`,
        params: {},
      })
      ElMessage({
        message: `删除成功！`,
        grouping: true,
        type: 'success',
      })
      emits('submited')
      dialogRef.value?.closeDialog()
    })
    .catch(() => {})
}

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped></style>
